//
// Created by LiuYou on 2021/10/31.
//

#include <iostream>
#include <unistd.h>
#include <cstring>
#include "MySemaphore.hpp"


static const int LEFT = 30000000;
static const int RIGHT = 30000200;
static const int THREAD_NUM = RIGHT - LEFT + 1;

/*
 * 限制同一时刻, 只能出现的线程的个数。
 */
static const int N = 4;


static pthread_t tidArray[THREAD_NUM];

static MySemaphore::MySem* mySem;


int main(int argc, char** argv) {


    mySem = MySemaphore::init( N );
    if (mySem == nullptr) {
        fprintf( stderr, "MySemaphore::init( N ): 失败了。\n" );
        return 1;
    }


    for (int i = LEFT; i <= RIGHT; ++i) {

        int* pInt = static_cast<int*>(malloc( sizeof( int )));
        *pInt = i;

        MySemaphore::requestResource( mySem, 1 );

        int errorNumber = pthread_create(
                tidArray + (i - LEFT), nullptr,
                [](void* args) -> void* {

                    int* pInt = static_cast<int*>(args);
                    int num = *pInt;

                    int mark{1};
                    for (int j = 2; j < num / 2; ++j) {
                        if (num % j == 0) {
                            mark = 0;
                            break;
                        }
                    }
                    if (mark == 1) {
                        printf( "%d 是一个质数。\n", num );
                    }

                    // 加 sleep();是为了看出效果。
                    // 每一个线程创建出来干活要超过5秒钟的时间。
                    sleep( 5 );

                    MySemaphore::returnResources( mySem, 1 );
                    pthread_exit( args );

                },
                pInt );

        if (errorNumber != 0) {
            fprintf( stderr, "pthread_create(): %s.\n", strerror(errno));
            return 1;
        }

    }

    for (int i = 0; i < THREAD_NUM; ++i) {
        void* threadReturn{};
        pthread_join( tidArray[i], &threadReturn );
        free( threadReturn );
    }

    MySemaphore::destroy( mySem );


    return 0;
}
